package db

import (
	"common/config"
	"common/logs"
	"context"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"time"
)

type MongoManager struct {
	Client *mongo.Client
	Db     *mongo.Database
}

func NewMongoManager() *MongoManager {
	mongoConf := config.Conf.Database.MongoConf
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	// 1. 设置 mongo 连接参数
	clientOptions := options.Client().ApplyURI(mongoConf.Url).
		SetAuth(options.Credential{Username: mongoConf.UserName, Password: mongoConf.Password}).
		SetMinPoolSize(mongoConf.MinPoolSize).SetMaxPoolSize(mongoConf.MaxPoolSize)
	// 2. 建立连接
	client, err := mongo.Connect(ctx, clientOptions)
	if err != nil {
		logs.Fatal("mongo connect error：%v", err)
	}
	// 3. ping 通服务
	if err := client.Ping(ctx, readpref.Primary()); err != nil {
		logs.Fatal("mongo ping error：%v", err)
	}
	return &MongoManager{
		Client: client,
		Db:     client.Database(mongoConf.Db),
	}
}

func (m *MongoManager) Close() {
	if err := m.Client.Disconnect(context.Background()); err != nil {
		logs.Error("mongo disconnect error：%v", err)
	}
}
